package net.ilikecoffee.myownsqlclient.models;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import com.mysql.jdbc.*;

public class Query {

	static private Connection conn = null;
	static private String urlConn = "jdbc:mysql://localhost:3306/";
	
	private List<String[]> results = null;
	
	static public void setUrlConn(String urlConn) {
		Query.urlConn = "jdbc:mysql://" + urlConn;
		Query.conn = null;
	}
	
	private static void initDB() throws SQLException {
		
		if (conn != null) return;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = (Connection)DriverManager.getConnection(urlConn,"root","");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public Query(String sql) throws SQLException {
		
		
		results = new LinkedList<String[]>();
		
		initDB();
		
		
		Statement stm = (Statement)conn.createStatement();
		boolean hasResultSet = stm.execute(sql);
		if (!hasResultSet) {
			return; 
		} 

		ResultSet rs = stm.getResultSet();

		ResultSetMetaData metadata = (ResultSetMetaData)rs.getMetaData();
		
		int numCols = metadata.getColumnCount();
		
		while (rs.next()) {
			String[] row = new String[numCols];
			
			for (int i=0;i<numCols;i++) {
				try {
				row[i] = rs.getString(i+1);
				} catch(SQLException e) {
					if (e.getErrorCode() != 0) {
						throw e;
					} else {
						row[i] = "0000-00-00 00:00:00";
					}
				}	
			}
			results.add(row);
		}
	}
	
	public static String getStatus() {
		try {
			initDB();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Properties p = conn.getProperties();

		return p.getProperty("HOST") + ":" + p.getProperty("PORT") + "/" + p.getProperty("DBNAME");
	}
	
	public List<String[]> getResults() {
		return results;
	}
}
